﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using Icst.Leaflike.Diagnotise;
using Icst.Leaflike.Searching;
using Icst.Leaflike.Logging;
using System.Threading;
using System.IO;

namespace Icst.Leaflike.Services
{
    public partial class SearchingService : ServiceBase, IDebugService
    {
        private ServiceHost _host;
        public SearchingService()
        {
            InitializeComponent();
            InitLogger();
            try
            {
                _host = new ServiceHost(typeof(SearchService));
            }
            catch (Exception e)
            {
                Logger.Error("FAILED TO CREATE SEARCHING SERVICE HOST. " + e.Message);
                throw;
            }
        }

        protected override void OnStart(string[] args)
        {

            try
            {
                Logger.Info("INIT SAFG");
                Logger.Info(AppConfig.SAFGcache);
                Logger.Info(AppConfig.SAFGclist);
                SAFGWrapper.Initialize(AppConfig.SAFGcache,AppConfig.SAFGclist);
            }
            catch (Exception e)
            {
                Logger.Error("FAILED TO INIT SAFG. " + e.Message);
                throw;
            }

            try
            {
                Logger.Info("START _host.Open");
                _host.Open();
            }
            catch (Exception e)
            {
                Logger.Error("FAILED TO _host.Open. " + e.Message);
                throw;
            }
        }

        protected override void OnStop()
        {
            try
            {
                Logger.Info("START _host.Close");
                _host.Close();
            }
            catch (Exception e)
            {
                Logger.Error("FAILED TO _host.Close. " + e.Message);
                throw;
            }
        }
        public void DebugStart() { OnStart(null); }
        public void DebugStop() { OnStop(); }
        private void InitLogger()
        {
            try
            {
                Logger.Initialize(Path.Combine(Thread.GetDomain().BaseDirectory, "log4net.config"));
            }
            catch { }
        }
    }
}
